package com.asktgapp.user.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.application.ApiUtil;
import com.asktgapp.application.Apiservice;
import com.asktgapp.architecture.retrofit.ApiException;
import com.asktgapp.architecture.retrofit.ApiResponseBody;
import com.asktgapp.architecture.rxjava.ExceptionHandle;
import com.asktgapp.base.BaseFragment;
import com.asktgapp.model.EngineerDetailVO;
import com.asktgapp.modulebase.common.adapter.BaseAdapter;
import com.asktgapp.modulebase.common.adapter.BaseViewHolder;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.modulebase.function.cameraroll.ImageLoader;
import com.asktgapp.user.activity.AskDetialActivity;
import com.asktgapp.user.activity.PayActivity;
import com.asktgapp.utils.ImageDisplayUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 工程师详情页面
 */

public class EngineerDetailFragment extends BaseFragment {

    @InjectView(R.id.recycle1)
    RecyclerView mRecyclerView;
    @InjectView(R.id.tv_like)
    TextView mHeartLike;
    @InjectView(R.id.tv_ask)
    TextView mAsk;
    @InjectView(R.id.tvReward)
    TextView tvReward;
    private BaseAdapter mBaseAdapter;
    private static final int TYPE_HEAD = 1;
    private static final int TYPE_PRICE = 2;
    private static final int TYPE_REASON = 3;
    private static final int TYPE_XG = 4;
    private static final int TYPE_ASK = 5;
    private String mId;
    private boolean isFollow = false;
    // 0:咨询 1:二手机评估 2:故障代检
    private int mType = 0;
    //0:支付宝 1:微信
    private int mPayType = 0;

    private double mMoney;

    EngineerDetailVO bean;

    private void setUI(EngineerDetailVO bean) {
//        if(getActivity().isFinishing())
//            return;
        //0没有关注 1关注
        if (bean.getIsFollow() == 0) {
            mHeartLike.setText("未关注");
            mHeartLike.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.weiguanzhu, 0, 0);
            isFollow = false;
        } else {
            mHeartLike.setText("已关注");
            mHeartLike.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.yiguanzh, 0, 0);
            isFollow = true;
        }
        mAsk.setText("立即咨询（¥ " + Utils.DtS(bean.getAdvisoryPrice()) + "元/次）");
        mMoney = bean.getAdvisoryPrice();
        List list = new ArrayList();
        Head head = new Head();
        head.setAttitude(bean.getEvaluate().getAttitude());
        head.setSpeed(bean.getEvaluate().getSpeed());
        head.setQuality(bean.getEvaluate().getQuality());
        head.setLabel(bean.getLabel());
        head.setRealname(bean.getRealname());
        head.setUsername(bean.getUsername());
        head.setUserPic(bean.getUserPic());
        list.add(0, head);
        Price price = new Price();
        price.setAdvisoryPrice(bean.getAdvisoryPrice());
        price.setDetectionPrice(bean.getDetectionPrice());
        price.setEvaluationPrice(bean.getEvaluationPrice());
        list.add(1, price);
        if (!Util.isEmpty(bean.getRecommendReason())) {
            Reason reason = new Reason();
            reason.setReason(bean.getRecommendReason());
            list.add(reason);
        }
//        if (bean.getQuestionList().size() > 0) {
//            list.add(new Xiangguan());
//            list.addAll(bean.getQuestionList());
//        }
        mBaseAdapter.setData(list);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        ViewGroup viewGroup = (ViewGroup) inflater.inflate(R.layout.fragment_engineer_detail, container, false);
        ButterKnife.inject(this, viewGroup);
        return super.onCreateView(inflater, viewGroup, savedInstanceState);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    @Override
    protected void initView(View rootView) {
        getBaseActivity().setBackNavigationIcon();
        mHeartLike.setOnClickListener(this);
        mAsk.setOnClickListener(this);
        tvReward.setOnClickListener(this);
        mId = getActivity().getIntent().getStringExtra("id");
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));
        mBaseAdapter = new BaseAdapter(getActivity()) {
            @Override
            public BaseViewHolder getViewHolder(ViewGroup parent, int viewType) {
                BaseViewHolder holder = null;
                if (viewType == TYPE_HEAD) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_engineer_head, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof Head) {
                                        Head bean = (Head) data;
                                        ImageView img = holder.getView(R.id.iv_engineer);
                                        ImageDisplayUtil.loadCircleHeadImage(getActivity(), img, bean.getUserPic());
                                        holder.setText(R.id.tv_engineer_name, bean.getRealname());
                                        holder.setText(R.id.tv_attitude, String.valueOf(bean.getAttitude()));
                                        holder.setText(R.id.tv_quality, String.valueOf(bean.getQuality()));
                                        holder.setText(R.id.tv_speed, String.valueOf(bean.getSpeed()));
                                        TextView mTag1 = holder.getView(R.id.tv_engineer_tag1);
                                        TextView mTag2 = holder.getView(R.id.tv_engineer_tag2);
                                        String[] str = bean.getLabel().split(",");
                                        if (str.length == 0) {
                                            mTag1.setVisibility(View.GONE);
                                            mTag2.setVisibility(View.GONE);
                                        } else if (str.length == 1) {
                                            if (Util.isEmpty(str[0])) {
                                                mTag1.setVisibility(View.GONE);
                                            } else {
                                                mTag1.setVisibility(View.VISIBLE);
                                            }
                                            mTag2.setVisibility(View.GONE);
                                            mTag1.setText(str[0]);
                                        } else if (str.length >= 2) {
                                            mTag1.setVisibility(View.VISIBLE);
                                            mTag2.setVisibility(View.VISIBLE);
                                            mTag1.setText(str[0]);
                                            mTag2.setText(str[1]);
                                        }
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {

                                }
                            });
                } else if (viewType == TYPE_PRICE) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_engineer_price, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof Price) {
                                        final Price bean = (Price) data;
//                                        holder.setText(R.id.tv_price11, String.valueOf(bean.getAdvisoryPrice()));
                                        holder.setText(R.id.tv_price11, Utils.D2S(bean.getAdvisoryPrice()));
                                        holder.setText(R.id.tv_price2, Utils.D2S(bean.getEvaluationPrice()));
                                        holder.setText(R.id.tv_price3, Utils.D2S(bean.getDetectionPrice()));
                                        final LinearLayout ll1 = holder.getView(R.id.ll1);
                                        final LinearLayout ll2 = holder.getView(R.id.ll2);
                                        final LinearLayout ll3 = holder.getView(R.id.ll3);
                                        ll1.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
                                                ll1.setBackgroundResource(R.mipmap.xiangqing_bg);
//                                                ll2.setBackgroundColor(Color.WHITE);
//                                                ll3.setBackgroundColor(Color.WHITE);
                                                mAsk.setText("立即咨询（¥ " + Utils.D2S(bean.getAdvisoryPrice()) + "元/次）");
                                                mType = 0;
                                                mMoney = bean.getAdvisoryPrice();
                                            }
                                        });
                                        ll2.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
//                                                ll1.setBackgroundColor(Color.WHITE);
//                                                ll2.setBackgroundResource(R.mipmap.xiangqing_bg);
//                                                ll3.setBackgroundColor(Color.WHITE);
//                                                mAsk.setText(getString(R.string.homePage_used_check) + "（¥ " + Utils.D2S(bean.getEvaluationPrice()) + "元/次）");
//                                                mType = 1;
//                                                mMoney = bean.getEvaluationPrice();
                                                showTost("暂未开通，不能点击付费", 0);
                                            }
                                        });
                                        ll3.setOnClickListener(new View.OnClickListener() {
                                            @Override
                                            public void onClick(View v) {
//                                                ll1.setBackgroundColor(Color.WHITE);
//                                                ll2.setBackgroundColor(Color.WHITE);
//                                                ll3.setBackgroundResource(R.mipmap.xiangqing_bg);
//                                                mAsk.setText(getString(R.string.homePage_problem_check) + "（¥ " + Utils.D2S(bean.getDetectionPrice()) + "元/次）");
//                                                mType = 2;
//                                                mMoney = bean.getDetectionPrice();
                                                showTost("暂未开通，不能点击付费", 0);

                                            }
                                        });


                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {

                                }
                            });
                } else if (viewType == TYPE_REASON) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_engineer_reason, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof Reason) {
                                        Reason bean = (Reason) data;
                                        holder.setText(R.id.tv_reason, bean.getReason());
                                    }
                                }

                                @Override
                                public void onItemClick(View view, int position) {

                                }
                            });
                } else if (viewType == TYPE_XG) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_engineer_xg, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {

                                }

                                @Override
                                public void onItemClick(View view, int position) {

                                }
                            });
                } else if (viewType == TYPE_ASK) {
                    holder = new BaseViewHolder(LayoutInflater.from(getActivity()).inflate(R.layout.item_engineer_ask, parent, false),
                            new BaseViewHolder.Callbacks() {
                                @Override
                                public void bind(BaseViewHolder holder, Object data) {
                                    if (data instanceof EngineerDetailVO.QuestionListBean) {
                                        EngineerDetailVO.QuestionListBean vo = (EngineerDetailVO.QuestionListBean) data;
                                        ImageView head = holder.getView(R.id.iv_answer_head);
                                        TextView mTag1 = holder.getView(R.id.tv_tag3);
                                        TextView mTag2 = holder.getView(R.id.tv_tag4);
                                        holder.setText(R.id.tv_zan, String.valueOf(vo.getLikeNumber()));
                                        holder.setText(R.id.tv_question, "【问答】" + vo.getQContent());
                                        holder.setText(R.id.tv_name, bean.getRealname());
                                        ImageDisplayUtil.LoadCircleImg(getActivity(), bean.getUserPic(), head);
                                        String[] str = bean.getLabel().split(",");
                                        if (str.length == 0) {
                                            mTag1.setVisibility(View.GONE);
                                            mTag2.setVisibility(View.GONE);
                                        } else if (str.length == 1) {
                                            if (Util.isEmpty(str[0])) {
                                                mTag1.setVisibility(View.GONE);
                                            } else {
                                                mTag1.setVisibility(View.VISIBLE);
                                            }
                                            mTag2.setVisibility(View.GONE);
                                            mTag1.setText(str[0]);
                                        } else if (str.length >= 2) {
                                            mTag1.setVisibility(View.VISIBLE);
                                            mTag2.setVisibility(View.VISIBLE);
                                            mTag1.setText(str[0]);
                                            mTag2.setText(str[1]);
                                        }
                                    }
                                    //// TODO: 2018/3/13  

                                }

                                @Override
                                public void onItemClick(View view, int position) {
                                    EngineerDetailVO.QuestionListBean vo = (EngineerDetailVO.QuestionListBean) mBaseAdapter.getData().get(position);
                                    Intent intent = new Intent(getActivity(), AskDetialActivity.class);
                                    intent.putExtra("id", String.valueOf(vo.getQId()));
                                    startActivity(intent);
                                }
                            });
                }

                return holder;
            }

            @Override
            public int getItemViewType(int position) {
                Object bean = mBaseAdapter.getData().get(position);
                if (bean instanceof Head) {
                    return TYPE_HEAD;
                } else if (bean instanceof Price) {
                    return TYPE_PRICE;
                } else if (bean instanceof Reason) {
                    return TYPE_REASON;
                } else if (bean instanceof Xiangguan) {
                    return TYPE_XG;
                } else if (bean instanceof EngineerDetailVO.QuestionListBean) {
                    return TYPE_ASK;
                }
                return 0;

            }
        };

        mRecyclerView.setAdapter(mBaseAdapter);
    }

    @Override
    public void loadData() {
        visibleLoading();
        HashMap params = new HashMap();
        params.put("id", mId);
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        Call<ApiResponseBody<EngineerDetailVO>> call =  ApiUtil.getInstance().create(Apiservice.class).getProjecter(params);
        call.enqueue(new Callback<ApiResponseBody<EngineerDetailVO>>() {
            @Override
            public void onResponse(Call<ApiResponseBody<EngineerDetailVO>> call, Response<ApiResponseBody<EngineerDetailVO>> response) {
                inVisibleLoading();
                if (response.isSuccessful()) {
                    bean = response.body().getResult();
                    setUI(bean);
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody<EngineerDetailVO>> call, Throwable t) {
                inVisibleLoading();
                visibleNoData();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }

            }
        });
        addSubscription(call);

    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.tv_like:
                // 0取消关注 1关注
                if (isFollow) {
                    doFollow(0);
                } else {
                    doFollow(1);
                }
                break;
            case R.id.tv_ask:
                if (PreferencesUtil.getBoolean(getActivity(), PreferencesUtil.KEY_IS_ENGINEER)) {
                    showTost("您已是工程师,目前不能咨询他人", 1);
                    return;
                }
                Intent intent = new Intent(getActivity(), PayActivity.class);
                intent.putExtra("type", mType);
                intent.putExtra("eg_user_id", bean.getId());
                intent.putExtra("money", mMoney);
                intent.putExtra("name", bean.getRealname());
                intent.putExtra("eg_pic", bean.getUserPic());
                startActivity(intent);
                getActivity().finish();

                break;
            case R.id.tvReward:

                break;
        }

    }

    private void doFollow(int i) {
        Apiservice apiservice = ApiUtil.getInstance().create();
        HashMap params = new HashMap();
        params.put("userid", PreferencesUtil.getString(getActivity(), PreferencesUtil.USER_ID));
        //0:二手机 1:设备出租 2:设备求租 3:工程师
        params.put("type", 3);
        params.put("temp", i);
        params.put("id", mId);
        showProgress(getClass().getSimpleName());
        Call<ApiResponseBody> call = apiservice.follow(params);
        call.enqueue(new Callback<ApiResponseBody>() {
            @Override
            public void onResponse(Call<ApiResponseBody> call, Response<ApiResponseBody> response) {
                dismissProgress();
                if (response.isSuccessful()) {
                    if (isFollow) {
                        mHeartLike.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.weiguanzhu, 0, 0);
                        mHeartLike.setText("未关注 ");
                    } else {
                        mHeartLike.setCompoundDrawablesWithIntrinsicBounds(0, R.mipmap.yiguanzh, 0, 0);
                        mHeartLike.setText("已关注");
                    }
                    isFollow = !isFollow;
                } else {
                    showTost(response.raw().message(), 1);
                }
            }

            @Override
            public void onFailure(Call<ApiResponseBody> call, Throwable t) {
                dismissProgress();
                ApiException apiException = ExceptionHandle.handleException(t);
                if (apiException.isTokenInvalid()) {
                    showUnLoginSnackbar();
                } else if (apiException.isNetConnected()) {
                    showSetNetworkSnackbar();
                } else {
                    showTost(apiException.getMessage(), 0);
                }
            }
        });
    }


    private class Xiangguan {
        private String tm;

        public String getTm() {
            return tm;
        }

        public void setTm(String tm) {
            this.tm = tm;
        }
    }

    private class Reason {
        private String reason;

        public String getReason() {
            return reason;
        }

        public void setReason(String reason) {
            this.reason = reason;
        }
    }

    private class Price {
        private double evaluationPrice;
        private double advisoryPrice;
        private double detectionPrice;

        public double getEvaluationPrice() {
            return evaluationPrice;
        }

        public void setEvaluationPrice(double evaluationPrice) {
            this.evaluationPrice = evaluationPrice;
        }

        public double getAdvisoryPrice() {
            return advisoryPrice;
        }

        public void setAdvisoryPrice(double advisoryPrice) {
            this.advisoryPrice = advisoryPrice;
        }

        public double getDetectionPrice() {
            return detectionPrice;
        }

        public void setDetectionPrice(double detectionPrice) {
            this.detectionPrice = detectionPrice;
        }
    }


    private class Head {
        private String username;
        private String userPic;
        private double attitude;
        private double speed;
        private double quality;
        private String label;
        private String realname;

        public String getUsername() {
            return username;
        }

        public void setUsername(String username) {
            this.username = username;
        }

        public String getUserPic() {
            return userPic;
        }

        public void setUserPic(String userPic) {
            this.userPic = userPic;
        }

        public String getLabel() {
            return label;
        }

        public void setLabel(String label) {
            this.label = label;
        }

        public String getRealname() {
            return realname;
        }

        public void setRealname(String realname) {
            this.realname = realname;
        }

        public double getAttitude() {
            return attitude;
        }

        public void setAttitude(double attitude) {
            this.attitude = attitude;
        }

        public double getSpeed() {
            return speed;
        }

        public void setSpeed(double speed) {
            this.speed = speed;
        }

        public double getQuality() {
            return quality;
        }

        public void setQuality(double quality) {
            this.quality = quality;
        }
    }
}
